#include "udp_blocks.h"

void UdpBlock::DeSerialize(string bk)
{
  char * pc, *pstart;
  pc = pstart = bk.c_str();
  memcpy(&m_usRequestId, pc, sizeof(unsigned short));
  pc += sizeof(unsigned short);
  memcpy(&m_uiSubRequestId, pc, sizeof(unsigned int));
  pc += sizeof(unsigned int);
  memcpy(&m_usBlockId, pc, sizeof(unsigned short));
  pc += sizeof(unsigned short);
  memcpy(&m_usBlocksTotal, pc, sizeof(unsigned short));
  pc += sizeof(unsigned short);
  m_strContent = bk.substr(size_t(pc-pstart));
}

UdpResponse::UdpResponse()
{
  m_usRequestId = 0;
  m_uiSubRequestId = 0;
  m_usBlocksTotal = 0;
  m_usBlocksReceived = 0;
  m_usBlocksToReceive = 0;
}

UdpResponse::~UdpResponse()
{
  m_usRequestId = 0;
  m_uiSubRequestId = 0;
  m_usBlocksTotal = 0;
  m_usBlocksReceived = 0;
  m_usBlocksToReceive = 0;
}

void UdpResponse::SetNumBlocks (unsigned short sz)
{
  m_vecBlocks.resize(sz);
}

void UdpResponse::Insert (UdpBlock* pblk)
{
  // if first block to this response
  if (m_usBlocksTotal == 0)
    {
      m_usRequestId = pblk->m_usRequestId;
      m_uiSubRequestId = pblk->m_uiSubRequestId;
      m_usBlocksTotal = pblk->m_usBlocksTotal;
      m_usBlocksReceived = 0;
      m_usBlocksToReceive = m_usBlocksTotal;
    }
  // not already exist
  if (m_vecBlocks[pblk.m_usBlockId] == NULL)
    {
      m_vecBlocks[pblk.m_usBlockId] = pblk;
	  m_usBlocksReceived ++;
	  m_usBlocksToReceive --;
	  assert(m_usBlocksToReceive >= 0);
    }
}

bool UdpResponse::IsComplete()
{
  return (m_usBlocksToReceive == 0);
}

bool UdpResponse::Exists(UdpBlock* pblk)
{
  return (m_vecBlocks[pblk->m_usBlockId] != NULL);
}

void UdpResponse::Output()
{
  
}
